const $ = require('./js/jquery.min');
window.$ = $;
window.jQuery = $;

(function () {
	'use strict';

	var $url = $("#url_box");
	var $path = $("#path_box");
	var $sync = $("#sync_btn");
	var $about = $("#about");

	var _outFolder = localStorage.getItem("outFolder") || "M:\\DK_Documents\\Mom";

	$url.val("http://www.kanyanqing.com/xiaoshuo/yanqing/5767/");
	$path.val(_outFolder);

	$sync.click(function () {
		var _url = $url.val();
		var _path = $path.val();

		$sync.prop("disabled", true);
		$about.text("连接中...");

		$.get(_url).then(function (data) {
			var $content = $("<div>" + data+ "</div>");
			var $summary = $content.find(".book_summary");
			var $aList = $content.find("table a");
			var _done = 0;

			var _summary = ($summary.text() || "").trim();
			var _title = $content.find(".book_title h1").text().trim();
			if(_title[0] === "《") _title = _title.slice(1);
			if(_title[_title.length - 1] === "》") _title = _title.slice(0, -1);
			$about.text("开始同步...");
			localStorage.setItem("outFolder", _path);

			var PromiseList = $aList.map(function () {
				var href = $(this).attr("href");
				return $.get(href).then(function (data) {
					var $content = $("<div>" + data+ "</div>");
					var _subTitle = $content.find(".book_title h1:nth(1)").text();
					var _content = $content.find("#zoom").text();
					_done += 1;
					$about.text("同步中...[" + _done + "/" + $aList.length + "]");
					return _subTitle + "\n" + _content;
				});
			});

			$.when.apply($, PromiseList).then(function () {
				var content = _summary + "\n\n\n";
				content += Array.prototype.join.call(arguments, "\n\n\n");
				content = content
					.replace(/\r\r/g, "\r")
					.replace(/\n\n/g, "\n");

				var PATH = require('path');
				var FS = require('fs');
				var _output = PATH.normalize(_path + "/" + _title + ".txt");
				FS.writeFile(_output, content, 'utf8', (err) => {
					if(err) {
						$about.text("保存失败:" + err);
					} else {
						$about.text("同步成功！");
					}
					$sync.prop("disabled", false);
				});
				$about.text("保存中...");
			}, function () {
				$about.text("同步失败，请重试...");
				$sync.prop("disabled", false);
			});
		}, function () {
			$sync.prop("disabled", false);
			$about.text("连接失败，请重试...");
		});
	});
})();
